package views.editor
{
    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.media.Microphone;
    import flash.media.Sound;
    import flash.net.FileFilter;
    import flash.net.FileReference;
    import flash.utils.ByteArray;
    
    import controllers.Prompt;
    
    import fr.kikko.lab.ShineMP3Encoder;
    
    import org.bytearray.micrecorder.MicRecorder;
    import org.bytearray.micrecorder.encoder.WaveEncoder;
    
    public class MP3Generator extends EventDispatcher
    {
        public function MP3Generator()
        {
        }
        
        public function record():void
        {
            var mic:Microphone=Microphone.getMicrophone();
            if(mic)
            {
                recorder=new MicRecorder( new WaveEncoder(),mic,60,44,0,1000)
                recorder.addEventListener(Event.COMPLETE, onRecordComplete);
                recorder.record();
            }
        }
        
        public function stopRecord():void
        {
            recorder.stop();
        }
        
        protected function onRecordComplete(event:Event):void
        {
            Prompt.showPrompt('转码中,请稍候...',false);
            var wavData:ByteArray=recorder.output;
            wavData.position=0;
            mp3Encoder = new ShineMP3Encoder(wavData);
            mp3Encoder.addEventListener(Event.COMPLETE, mp3EncodeComplete);
            mp3Encoder.start();
        }
        
        private function mp3EncodeComplete(e:Event):void
        {
            mp3BA=mp3Encoder.mp3Data;
            mp3BA.position=0;
            snd=new Sound();
            snd.loadCompressedDataFromByteArray(mp3BA,mp3BA.length);
            
            Prompt.hide();
            dispatchEvent(new Event(Event.COMPLETE));
        }
        
        public function loadFile():void
        {
            fref=new FileReference();
            fref.browse([new FileFilter("请选择音频","*.mp3")]);
            fref.addEventListener(Event.SELECT,onSelected);
        }
        
        protected function onSelected(event:Event):void
        {
            fref.load();
            fref.addEventListener(Event.COMPLETE,onComplete);
        }
        
        protected function onComplete(event:Event):void
        {
            mp3BA = fref.data;
            mp3BA.position=0;
            snd=new Sound();
            snd.loadCompressedDataFromByteArray(mp3BA,mp3BA.length);
            dispatchEvent(new Event(Event.COMPLETE));
        }
        
        public function getBA():ByteArray
        {
            return mp3BA;
        }
        
        public function getSound():Sound
        {
            return snd;
        }
        
        private var snd:Sound;
        private var mp3BA:ByteArray;
        
        private var fref:FileReference;
        private var recorder:MicRecorder;
        private var mp3Encoder:ShineMP3Encoder;
    }
}

